import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '../components/Login.vue'
import Home from '../components/Home.vue'
import Welcome from '../components/Welcome.vue'
import Users from '../components/user/Users.vue'
import test from '../components/test'
import Firstline from '../components/line/Firstline'
import Robotview from '../components/robot/Robotview'
import Register from '../components/Register'
import historytable from '../components/history/historytable'
import abnormaltable from '../components/abnormal/abnormaltable'
import management from '../components/account/management'

Vue.use(VueRouter)

const routes = [
    // 重定向，当访问根路径的时候，自动跳转到登录组件的路径
    { path: '/', redirect: '/login' },
    { path: '/login', component: Login},
    { path: '/test', component: test },
    { path: '/register', component: Register },
    {
        path: '/home', component: Home,
        redirect: '/welcome',
        // 子路由
        children: [
            { path: '/welcome', component: Welcome },
            { path: '/users', component: Users },
            { path: '/firstline', component: Firstline },
            { path: '/robotview', component: Robotview },
            { path: '/history', component: historytable },
            { path: '/abnormal', component: abnormaltable },
            { path: '/management', component: management },
        ]
    },
]

const router = new VueRouter({
  routes
})

//路由导航守卫，控制路由访问权限
//原理：在前端实现和后端无关，当没有sessionStorage里面没有token时候，不能跳转各页面
router.beforeEach((to, from, next) => {
    //如果要去登录页，直接跳转
    if (to.path === '/register') return next()
    if (to.path === '/login') return next()

    // 如果要去其他页面，得先从 sessionStorage 里面拿token
    const tokenStr = window.sessionStorage.getItem('token')
    // 如果有 token，就可以给他跳转
    if (!tokenStr) return next('/login')
    next()
})

export default router
